// https://leetcode.cn/problems/fruit-into-baskets/submissions/558827958/

class Solution {
public:
    int totalFruit(vector<int>& fruits) {
        int l = 0, r = 0;
        int ans = 0;

        vector<int>& v = fruits;

        int n = v.size();
        unordered_map<int, int> s;
        while (r < n && l < n) {
            s[v[r]]++;
            if (s.size() <= 2) {
                ans = max(ans, r-l+1);
                r++;
            } else {
                s[v[l]]--;
                s[v[r]]--;
                if (s[v[l]] <= 0) {
                    s.erase(v[l]);
                }
                l++;
            }
        }
        return ans;
    }
};